package com.ai.zhipu;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * zhipu api
 * @author houwenpeng
 */
public class ZPAi {


    public static void main(String[] args) {
        String apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions"; // 官网中说明文档的URL
        String apiKey = "3573dba746fb4fc384b768182a98b790.pYKX7zskd9lzVKvS"; // 你的API密钥
        String inputText = "一个袋子中有5个红球和3个蓝球,随机抽取2个球,抽到至少1个红球的概率为多少"; // 你想要问答的内容

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setDoOutput(true);

            // 创建请求体
            String jsonInputString = "{\"model\": \"glm-4\", \"messages\": [{\"role\": \"user\", \"content\": \"" + inputText + "\"}]}";

            // 发送请求体
            try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) {
                os.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String responseLine;
                    StringBuilder response = new StringBuilder();

                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    System.out.println("Response: " + response.toString());
                }
            } else {
                System.out.println("Failed to call GLM-4 API");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
